package com.example.library.adminfragment;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.library.BlacklistActivity;
import com.example.library.DatabaseHelper;
import com.example.library.R;
import com.example.library.User;
import com.example.library.adapter.UserAdapter;
import com.example.library.util.BlacklistReasonManager;

import java.util.ArrayList;
import java.util.List;

public class AdminUserFragment extends Fragment implements UserAdapter.OnUserActionListener {
    private RecyclerView rvUsers;
    private EditText etSearch;
    private Spinner spinnerUserType, spinnerStatus;
    private Button btnBlacklist;
    private UserAdapter adapter;
    private List<User> allUsers;
    private List<User> filteredUsers;
    private DatabaseHelper dbHelper;
    private Handler searchHandler = new Handler();
    private Runnable searchRunnable;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.admin_user, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        try {
            initViews(view);
            setupListeners();
            setupSpinners();
            loadAllUsers();
        } catch (Exception e) {
            Log.e("AdminUserFragment", "Error in onViewCreated", e);
            Toast.makeText(getContext(), "初始化界面失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    private void initViews(View view) {
        try {
            rvUsers = view.findViewById(R.id.rv_users);
            etSearch = view.findViewById(R.id.et_search);
            spinnerUserType = view.findViewById(R.id.spinner_user_type);
            spinnerStatus = view.findViewById(R.id.spinner_status);
            btnBlacklist = view.findViewById(R.id.btn_blacklist);
            
            if (rvUsers != null) {
                rvUsers.setLayoutManager(new LinearLayoutManager(getContext()));
            }
        } catch (Exception e) {
            Log.e("AdminUserFragment", "Error in initViews", e);
            throw e;
        }
    }

    private void setupListeners() {
        if (etSearch != null) {
            etSearch.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (searchRunnable != null) searchHandler.removeCallbacks(searchRunnable);
                    searchRunnable = () -> filterUsers();
                    searchHandler.postDelayed(searchRunnable, 300);
                }
                @Override
                public void afterTextChanged(Editable s) {}
            });
        }

        if (spinnerUserType != null) {
            spinnerUserType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    filterUsers();
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {}
            });
        }

        if (spinnerStatus != null) {
            spinnerStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    filterUsers();
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {}
            });
        }

        if (btnBlacklist != null) {
            btnBlacklist.setOnClickListener(v -> {
                try {
                    Intent intent = new Intent(getContext(), BlacklistActivity.class);
                    startActivity(intent);
                } catch (Exception e) {
                    Log.e("AdminUserFragment", "Error starting BlacklistActivity", e);
                    Toast.makeText(getContext(), "无法打开黑名单界面", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void setupSpinners() {
        try {
            if (spinnerUserType != null && getContext() != null) {
                String[] userTypes = {"全部", "学生", "管理员"};
                ArrayAdapter<String> userTypeAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, userTypes);
                userTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerUserType.setAdapter(userTypeAdapter);
            }

            if (spinnerStatus != null && getContext() != null) {
                String[] statuses = {"全部", "正常", "禁用", "黑名单"};
                ArrayAdapter<String> statusAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, statuses);
                statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerStatus.setAdapter(statusAdapter);
            }
        } catch (Exception e) {
            Log.e("AdminUserFragment", "Error in setupSpinners", e);
            Toast.makeText(getContext(), "初始化筛选器失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void loadAllUsers() {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            if (getContext() == null) {
                Log.e("AdminUserFragment", "Context is null in loadAllUsers");
                return;
            }

            dbHelper = new DatabaseHelper(getContext());
            allUsers = new ArrayList<>();
            filteredUsers = new ArrayList<>();

            db = dbHelper.getReadableDatabase();
            cursor = db.query("user", null, null, null, null, null, null);

            if (cursor != null && cursor.getColumnCount() > 0) {
                // 获取列索引
                int idIndex = cursor.getColumnIndex("id");
                int nameIndex = cursor.getColumnIndex("name");
                int studentIdIndex = cursor.getColumnIndex("studentId");
                int contactIndex = cursor.getColumnIndex("contact");
                int userTypeIndex = cursor.getColumnIndex("userType");
                int creditScoreIndex = cursor.getColumnIndex("creditScore");
                int statusIndex = cursor.getColumnIndex("status");

                // 检查必要的列是否存在
                if (idIndex == -1 || nameIndex == -1 || studentIdIndex == -1 || 
                    userTypeIndex == -1 || statusIndex == -1) {
                    throw new Exception("数据库结构不正确，缺少必要的列");
                }

                while (cursor.moveToNext()) {
                    User user = new User();
                    user.setId(cursor.getInt(idIndex));
                    user.setName(cursor.getString(nameIndex));
                    user.setStudentId(cursor.getString(studentIdIndex));
                    
                    // 对可选列使用安全的获取方式
                    if (contactIndex != -1) {
                        user.setContact(cursor.getString(contactIndex));
                    }
                    user.setUserType(cursor.getString(userTypeIndex));
                    if (creditScoreIndex != -1) {
                        user.setCreditScore(cursor.getInt(creditScoreIndex));
                    }
                    user.setStatus(cursor.getInt(statusIndex));
                    
                    allUsers.add(user);
                }
            }

            filteredUsers.addAll(allUsers);
            
            if (rvUsers != null && getContext() != null) {
                adapter = new UserAdapter(getContext(), filteredUsers, this);
                rvUsers.setAdapter(adapter);
            }

        } catch (Exception e) {
            Log.e("AdminUserFragment", "Error loading users: " + e.getMessage(), e);
            if (getContext() != null) {
                Toast.makeText(getContext(), "加载用户数据失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
    }

    private void filterUsers() {
        try {
            if (etSearch == null || spinnerUserType == null || spinnerStatus == null || adapter == null) {
                return;
            }

            String searchText = etSearch.getText().toString().trim().toLowerCase();
            String selectedUserType = spinnerUserType.getSelectedItem().toString();
            String selectedStatus = spinnerStatus.getSelectedItem().toString();
            
            filteredUsers.clear();
            
            for (User user : allUsers) {
                if (user == null) continue;
                
                boolean matchesSearch = searchText.isEmpty() ||
                    (user.getName() != null && user.getName().toLowerCase().contains(searchText)) ||
                    (user.getStudentId() != null && user.getStudentId().toLowerCase().contains(searchText));
                    
                boolean matchesUserType = selectedUserType.equals("全部") || 
                    (user.getUserType() != null && user.getUserType().equals(selectedUserType));
                    
                boolean matchesStatus = selectedStatus.equals("全部") ||
                    (selectedStatus.equals("正常") && user.getStatus() == 1) ||
                    (selectedStatus.equals("禁用") && user.getStatus() == 0) ||
                    (selectedStatus.equals("黑名单") && user.getStatus() == 2);

                if ((searchText.isEmpty() || matchesSearch) && matchesUserType && matchesStatus) {
                    filteredUsers.add(user);
                }
            }
            
            adapter.notifyDataSetChanged();
            
        } catch (Exception e) {
            Log.e("AdminUserFragment", "Error filtering users", e);
        }
    }

    @Override
    public void onDisableUser(User user) {
        if (getContext() == null || user == null) return;
        
        new AlertDialog.Builder(getContext())
            .setTitle("禁用用户")
            .setMessage("确定要禁用 " + user.getName() + " 吗？")
            .setPositiveButton("确定", (dialog, which) -> {
                updateUserStatus(user, 0);
            })
            .setNegativeButton("取消", null)
            .show();
    }

    @Override
    public void onEnableUser(User user) {
        if (getContext() == null || user == null) return;
        
        new AlertDialog.Builder(getContext())
            .setTitle("启用用户")
            .setMessage("确定要启用 " + user.getName() + " 吗？")
            .setPositiveButton("确定", (dialog, which) -> {
                updateUserStatus(user, 1);
            })
            .setNegativeButton("取消", null)
            .show();
    }

    @Override
    public void onAddToBlacklist(User user) {
        if (getContext() == null || user == null) return;
        
        final String[] reasons = {"违纪", "超时", "冒用", "其他"};
        new AlertDialog.Builder(getContext())
            .setTitle("请选择加入黑名单原因")
            .setSingleChoiceItems(reasons, 0, null)
            .setPositiveButton("确定", (dialog, which) -> {
                AlertDialog ad = (AlertDialog) dialog;
                int selected = ad.getListView().getCheckedItemPosition();
                String reason = reasons[selected];
                BlacklistReasonManager.setReason(getContext(), user.getId(), reason);
                updateUserStatus(user, 2);
            })
            .setNegativeButton("取消", null)
            .show();
    }

    @Override
    public void onRemoveFromBlacklist(User user) {
        if (getContext() == null || user == null) return;
        
        new AlertDialog.Builder(getContext())
            .setTitle("移出黑名单")
            .setMessage("确定要将 " + user.getName() + " 移出黑名单吗？")
            .setPositiveButton("确定", (dialog, which) -> {
                updateUserStatus(user, 1);
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void updateUserStatus(User user, int newStatus) {
        if (getContext() == null || user == null || dbHelper == null) return;
        
        SQLiteDatabase db = null;
        try {
            db = dbHelper.getWritableDatabase();
            android.content.ContentValues values = new android.content.ContentValues();
            values.put("status", newStatus);
            int result = db.update("user", values, "id = ?", new String[]{String.valueOf(user.getId())});
            
            if (result > 0) {
                user.setStatus(newStatus);
                String statusText = "";
                switch (newStatus) {
                    case 0:
                        statusText = "已禁用";
                        break;
                    case 1:
                        statusText = "已启用";
                        break;
                    case 2:
                        statusText = "已加入黑名单";
                        break;
                }
                Toast.makeText(getContext(), "用户" + statusText, Toast.LENGTH_SHORT).show();
                filterUsers();
            } else {
                Toast.makeText(getContext(), "操作失败，请重试", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e("AdminUserFragment", "Error updating user status", e);
            Toast.makeText(getContext(), "更新用户状态失败", Toast.LENGTH_SHORT).show();
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }

    @Override
    public void onViewDetails(User user) {
        if (getContext() == null || user == null) return;
        
        new AlertDialog.Builder(getContext())
            .setTitle("用户详情")
            .setMessage("姓名：" + user.getName() + "\n" +
                    "学号：" + user.getStudentId() + "\n" +
                    "联系方式：" + user.getContact() + "\n" +
                    "身份：" + user.getUserType() + "\n" +
                    "信用分：" + user.getCreditScore())
            .setPositiveButton("确定", null)
            .show();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isAdded()) {
            loadAllUsers();
        }
    }
} 